package com.cxs.biyesheji.Interceptor;

import com.cxs.biyesheji.pojo.Customer;
import com.cxs.biyesheji.service.OrderItemService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Arrays;

/**
 * 前台登陆状态拦截器  如果访问的请求没有在noNeedAuthPage数组就跳转登陆
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    OrderItemService orderItemService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        String contextPath=session.getServletContext().getContextPath()+"/fore";
        String[] noNeedAuthPage = new String[]{
                "Index",
                "DetailUI",
                "RegisterUI",
                "Register",
                "LoginUI",
                "Login",
                "IsLogin",
                "MtLogin",
                "CstLoginOut",
                "DelOrderItem",
                "CreateOrder",
                "Payed",
                "NameLike",
                "FindCategory",
                "Zixunadd",
                "LoginMsg",
                "addUser",
                "alipay",
                "pay"
        };
        String uri = request.getRequestURI();
        uri = uri.substring(5,uri.length());
        if(uri.startsWith("/fore")){
            String method = StringUtils.substringAfterLast(uri,"/fore" );
            if(!Arrays.asList(noNeedAuthPage).contains(method)){
                Customer customer =(Customer) session.getAttribute("cst");
                if(null==customer){
                    response.sendRedirect("foreLoginUI");
                    return false;
                }
            }
        }

        return true;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
